package main

import (
	"context"
	"gitee.com/sdynasty/yogurt"
	_ "gitee.com/sdynasty/yogurt/encoding/json"
	"gitee.com/sdynasty/yogurt/log"
	"gitee.com/sdynasty/yogurt/transport/http"
	"github.com/gin-gonic/gin"
)

func main() {
	app := initApp()
	if err := app.Run(); err != nil {
		panic(err)
	}
}

func initApp() *yogurt.App {
	return yogurt.New(yogurt.Server(http.NewServer(http.Address(":9999"), http.EngineFitment(engineFitment))))
}

func engineFitment(g *gin.Engine, cw http.GinAdapter) {
	g.GET("hello", demoToolHandlerHello(cw))
}

type helloReq struct {
	In string `form:"in" json:"in"`
}
type helloReply struct {
	Out string `json:"out"`
}

// 将ginHandler转换成通用Handler
func demoToolHandlerHello(cw http.GinAdapter) gin.HandlerFunc {
	return func(c *gin.Context) {
		var ct = cw.FromGinContext(c)
		v := new(helloReq)
		if err := ct.Bind(v); err != nil {
			c.Error(err)
			return
		}

		h := ct.Middleware(func(ctx context.Context, req any) (any, error) {
			return helloFunc(ctx, req.(*helloReq))
		})
		out, err := h(ct, v)
		if err != nil {
			c.Error(err)
		}
		cw.Payload(c, out)
	}
}
func helloFunc(ctx context.Context, req *helloReq) (*helloReply, error) {
	log.Debug("REQ in = ", req.In)

	return &helloReply{
		Out: "copy from " + req.In,
	}, nil
}
